package sever

import (
	"context"
	"encoding/json"
	"fmt"
	"strconv"
	"takeout-ordering/common/initialize"
	takeout "takeout-ordering/common/proto"
	"takeout-ordering/pkg"
	"takeout-ordering/rpc/models"
	"time"
)

func UserRegister(in *takeout.UserRegisterReq) (*takeout.UserRegisterResp, error) {
	u := models.User{}

	mobile, _ := u.FindUserMobile(in.Mobile)
	if mobile != nil {
		return nil, fmt.Errorf("注册失败,该用户已注册")
	}

	_, err := u.CreateUser(in)
	if err != nil {
		return nil, fmt.Errorf("注册失败")
	}

	return &takeout.UserRegisterResp{
		Success: true,
	}, nil

}
func UserLogin(in *takeout.UserLoginReq) (*takeout.UserLoginResp, error) {
	u := models.User{}

	mobile, _ := u.FindUserMobile(in.Mobile)
	if mobile == nil {
		return nil, fmt.Errorf("登录失败,该用户未注册")
	}

	if in.Password != mobile.Password {
		return nil, fmt.Errorf("登录失败,密码错误")
	}
	return &takeout.UserLoginResp{
		UserId: int64(mobile.ID),
	}, nil

}
func MealsList(in *takeout.MealsListReq) (*takeout.MealsListResp, error) {
	m := models.Meals{}

	var all []*takeout.MealsList

	var list []*models.Meals
	var err error

	//如果redis当中已存在直接读取
	get, err := initialize.Client.Get(context.Background(), "MealsList").Result()
	if err == nil {
		var take takeout.MealsListResp
		err = json.Unmarshal([]byte(get), &take)
		if err == nil {
			return nil, err
		}
		initialize.Client.Del(context.Background(), "MealsList")

	}
	if in.Types == 0 {
		list, err = m.FindMealsList()
		if err != nil {
			return nil, fmt.Errorf("餐品查询失败")
		}
	} else {
		list, err = m.FindMealsLists(in.Types)
		if err != nil {
			return nil, fmt.Errorf("餐品查询失败")
		}
	}

	for _, i := range list {
		all = append(all, &takeout.MealsList{
			MealsId: int64(i.ID),
			Name:    i.Name,
			Price:   float32(i.Price),
			Stock:   i.Stock,
			Types:   i.Types,
			Img:     i.Img,
		})
	}

	marshal, err := json.Marshal(all)
	if err != nil {
		return nil, fmt.Errorf("序列化失败")
	}
	//设置redis缓存和过期时间
	initialize.Client.Set(context.Background(), "MealsList", marshal, time.Minute*30)

	return &takeout.MealsListResp{
		List: all,
	}, nil
}

func CreateOrder(in *takeout.CreateOrderReq) (*takeout.CreateOrderResp, error) {
	m := models.Meals{}
	o := models.Order{}
	c := models.Coupon{}

	var order *models.Order
	var pon *takeout.UserCouPon

	//findOrder, _ := o.FindOrder(in.UserId)
	//if findOrder != nil {
	//	return nil, fmt.Errorf("用户不能重复创建")
	//}

	meals, err := m.FindMeals(in.MealsId)
	if err != nil {
		return nil, fmt.Errorf("没有该菜品信息")
	}

	stock := meals.Stock - in.Num

	if stock < 0 {
		return nil, fmt.Errorf("%s库存不足", meals.Name)
	}

	if in.CouponId != 0 {
		pon, err = c.FindUserCouPon(in.UserId, in.CouponId)
		if pon == nil {
			return nil, fmt.Errorf("没有该优惠卷")
		}

		order, err = o.CreateOrder(in, meals, stock, pon.Minus)
		if err != nil {
			return nil, fmt.Errorf("订单创建失败")
		}
	} else {
		order, err = o.CreateOrders(in, meals, stock)
		if err != nil {
			return nil, fmt.Errorf("订单创建失败")
		}
	}

	return &takeout.CreateOrderResp{
		OrderId: int64(order.ID),
	}, nil

}
func OrderPay(in *takeout.OrderPayReq) (*takeout.OrderPayResp, error) {
	o := models.Order{}

	m := models.Meals{}

	order, err := o.FindOrder(in.OrderId)
	if err != nil {
		return nil, fmt.Errorf("没有该订单信息")
	}

	meals, err := m.FindMeals(order.MealsId)
	if err != nil {
		return nil, fmt.Errorf("餐品信息查询失败")
	}

	float := strconv.FormatFloat(order.Price, 'f', -1, 64)

	//pay := pkg.NewAlipay().Pay(meals.Name, order.OrderSn, float)

	pay := pkg.Zhifu(meals.Name, order.OrderSn, float)

	return &takeout.OrderPayResp{Url: pay}, nil
}

func Payback(in *takeout.PaybackReq) (*takeout.PaybackResp, error) {
	o := models.Order{}
	u := models.User{}

	_, err := o.UpdateStatus(in.OrderSn, in.Status)
	if err != nil {
		return nil, fmt.Errorf("修改状态失败")
	}
	sn, err := o.FindOrderSn(in.OrderSn)
	if err != nil {
		return nil, fmt.Errorf("订单查找失败")
	}

	user, err := u.FindUserMobiles(sn.UserId)
	if err != nil {
		return nil, fmt.Errorf("积分查找失败")
	}

	Points := user.Points + in.Points

	_, err = u.Updatepoints(sn.UserId, Points)
	if err != nil {
		return nil, fmt.Errorf("积分添加失败")
	}

	return &takeout.PaybackResp{Success: true}, nil

}
func FindCoupon(in *takeout.FindCouponReq) (*takeout.FindCouponResp, error) {
	c := models.Coupon{}
	pons, err := c.FindUserCouPons(in.UserId)
	if err != nil {
		return nil, fmt.Errorf("查找优惠卷失败")
	}
	var all []*takeout.UserCouPon

	for _, p := range pons {
		all = append(all, &takeout.UserCouPon{
			Name:      p.Name,
			StartTime: p.StartTime,
			EndTime:   p.EndTime,
			Full:      p.Full,
			Minus:     p.Minus,
			UserId:    p.UserId,
			CouponId:  p.CouponId,
			Status:    p.Status,
		})
	}
	return &takeout.FindCouponResp{List: all}, nil
}
func UserOrderList(in *takeout.UserOrderListReq) (*takeout.UserOrderListResp, error) {
	o := models.Order{}

	order, err := o.FindOrders(in.UserId)
	if err != nil {
		return nil, fmt.Errorf("订单查询失败")
	}
	var all []*takeout.UserOrderList

	for _, i := range order {
		all = append(all, &takeout.UserOrderList{
			MealsId:  i.MealsId,
			UserId:   i.UserId,
			CouponId: i.CouponId,
			OrderSn:  i.OrderSn,
			Sum:      i.Sum,
			Price:    float32(i.Price),
			Notes:    i.Notes,
			Status:   i.Status,
			Pay:      i.Pay,
		})
	}
	return &takeout.UserOrderListResp{List: all}, nil

}
func CouPonReceive(in *takeout.CouPonReceiveReq) (*takeout.CouPonReceiveResp, error) {
	c := models.Coupon{}

	u := models.UserCoupon{}

	pon, _ := c.FindUserCouPon(in.UserId, in.CouPonId)
	if pon != nil {
		return nil, fmt.Errorf("该用户不可重复领取")
	}

	_, err := u.CreateCoupon(in)
	if err != nil {
		return nil, fmt.Errorf("该用户领取失败")
	}

	return &takeout.CouPonReceiveResp{Success: true}, nil
}
